using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Data;
using System.Globalization;
using System.Reflection;
using System.Security.Permissions;
using System.Web.UI;
using System.Web.UI.Design;
using System.Web.UI.Design.WebControls;
using System.Web.UI.WebControls;
using System.Windows.Forms;
using Microsoft.Web.Design;

namespace MyDesigner
{
#region ObjectDataSource
	//[PersistChildren(false),
	// Designer(
	//  "System.Web.UI.Design.WebControls.MyODSDesigner, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
	//  ),
	// ParseChildren(true), DefaultEvent("Selecting"),
	// ToolboxBitmap(typeof(ObjectDataSource)),
	//  //WebSysDescription("ObjectDataSource_Description"), 
	//  //WebSysDisplayName("ObjectDataSource_DisplayName"), 
	// DefaultProperty("TypeName"),
	// AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal),
	// AspNetHostingPermission(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
	//public class ObjectDataSource : DataSourceControl
	//{
	//  // Fields
	//  //private SqlDataSourceCache _cache;
	//  private ObjectDataSourceView _view;
	//  private ICollection _viewNames;
	//  private const string DefaultViewName = "DefaultView";

	//  // Events
	//  //[WebCategory("Data"), WebSysDescription("DataSource_Deleted")]
	//  public event ObjectDataSourceStatusEventHandler Deleted
	//  {
	//    add { this.GetView().Deleted += value; }
	//    remove { this.GetView().Deleted -= value; }
	//  }

	//  //[WebSysDescription("DataSource_Deleting"), WebCategory("Data")]
	//  public event ObjectDataSourceMethodEventHandler Deleting
	//  {
	//    add { this.GetView().Deleting += value; }
	//    remove { this.GetView().Deleting -= value; }
	//  }

	//  //[WebCategory("Data"), WebSysDescription("DataSource_Filtering")]
	//  public event ObjectDataSourceFilteringEventHandler Filtering
	//  {
	//    add { this.GetView().Filtering += value; }
	//    remove { this.GetView().Filtering -= value; }
	//  }

	//  //[WebCategory("Data"), WebSysDescription("DataSource_Inserted")]
	//  public event ObjectDataSourceStatusEventHandler Inserted
	//  {
	//    add { this.GetView().Inserted += value; }
	//    remove { this.GetView().Inserted -= value; }
	//  }

	//  //[WebSysDescription("DataSource_Inserting"), WebCategory("Data")]
	//  public event ObjectDataSourceMethodEventHandler Inserting
	//  {
	//    add { this.GetView().Inserting += value; }
	//    remove { this.GetView().Inserting -= value; }
	//  }

	//  //[WebSysDescription("ObjectDataSource_ObjectCreated"), WebCategory("Data")]
	//  public event ObjectDataSourceObjectEventHandler ObjectCreated
	//  {
	//    add { this.GetView().ObjectCreated += value; }
	//    remove { this.GetView().ObjectCreated -= value; }
	//  }

	//  //[WebSysDescription("ObjectDataSource_ObjectCreating"), WebCategory("Data")]
	//  public event ObjectDataSourceObjectEventHandler ObjectCreating
	//  {
	//    add { this.GetView().ObjectCreating += value; }
	//    remove { this.GetView().ObjectCreating -= value; }
	//  }

	//  //[WebCategory("Data"), WebSysDescription("ObjectDataSource_ObjectDisposing")]
	//  public event ObjectDataSourceDisposingEventHandler ObjectDisposing
	//  {
	//    add { this.GetView().ObjectDisposing += value; }
	//    remove { this.GetView().ObjectDisposing -= value; }
	//  }

	//  //[WebCategory("Data"), WebSysDescription("ObjectDataSource_Selected")]
	//  public event ObjectDataSourceStatusEventHandler Selected
	//  {
	//    add { this.GetView().Selected += value; }
	//    remove { this.GetView().Selected -= value; }
	//  }

	//  //[WebCategory("Data"), WebSysDescription("ObjectDataSource_Selecting")]
	//  public event ObjectDataSourceSelectingEventHandler Selecting
	//  {
	//    add { this.GetView().Selecting += value; }
	//    remove { this.GetView().Selecting -= value; }
	//  }

	//  //[WebSysDescription("DataSource_Updated"), WebCategory("Data")]
	//  public event ObjectDataSourceStatusEventHandler Updated
	//  {
	//    add { this.GetView().Updated += value; }
	//    remove { this.GetView().Updated -= value; }
	//  }

	//  //[WebCategory("Data"), WebSysDescription("DataSource_Updating")]
	//  public event ObjectDataSourceMethodEventHandler Updating
	//  {
	//    add { this.GetView().Updating += value; }
	//    remove { this.GetView().Updating -= value; }
	//  }

	//  // Methods
	//  public ObjectDataSource()
	//  {
	//  }

	//  public ObjectDataSource(string typeName, string selectMethod)
	//  {
	//    this.TypeName = typeName;
	//    this.SelectMethod = selectMethod;
	//  }

	//  internal string CreateCacheKey(int startRowIndex, int maximumRows)
	//  {
	//    StringBuilder builder = this.CreateRawCacheKey();
	//    builder.Append(':');
	//    builder.Append(startRowIndex.ToString(CultureInfo.InvariantCulture));
	//    builder.Append(':');
	//    builder.Append(maximumRows.ToString(CultureInfo.InvariantCulture));
	//    return builder.ToString();
	//  }

	//  internal string CreateMasterCacheKey()
	//  {
	//    return this.CreateRawCacheKey().ToString();
	//  }

	//  private StringBuilder CreateRawCacheKey()
	//  {
	//    StringBuilder builder = new StringBuilder("u", 0x400);
	//    builder.Append(base.GetType().GetHashCode().ToString(CultureInfo.InvariantCulture));
	//    builder.Append(":");
	//    //builder.Append(this.CacheDuration.ToString(CultureInfo.InvariantCulture));
	//    //builder.Append(':');
	//    //builder.Append(((int) this.CacheExpirationPolicy).ToString(CultureInfo.InvariantCulture));
	//    //builder.Append(":");
	//    //builder.Append(this.SqlCacheDependency);
	//    //builder.Append(":");
	//    builder.Append(this.TypeName);
	//    builder.Append(":");
	//    builder.Append(this.SelectMethod);
	//    if (this.SelectParameters.Count > 0)
	//    {
	//      builder.Append("?");
	//      foreach (DictionaryEntry entry in this.SelectParameters.GetValues(this.Context, this))
	//      {
	//        builder.Append(entry.Key.ToString());
	//        if ((entry.Value != null) && (entry.Value != DBNull.Value))
	//        {
	//          builder.Append("=");
	//          builder.Append(entry.Value.ToString());
	//        }
	//        else if (entry.Value == DBNull.Value)
	//        {
	//          builder.Append("(dbnull)");
	//        }
	//        else
	//        {
	//          builder.Append("(null)");
	//        }
	//        builder.Append("&");
	//      }
	//    }
	//    return builder;
	//  }

	//  public int Delete()
	//  {
	//    return this.GetView().Delete(null, null);
	//  }

	//  private ObjectDataSourceView GetView()
	//  {
	//    if (this._view == null)
	//    {
	//      System.Web.UI.WebControls.ObjectDataSource ods =
	//        new System.Web.UI.WebControls.ObjectDataSource();
	//      this._view = new ObjectDataSourceView(ods, "DefaultView", this.Context);
	//      if (base.IsTrackingViewState)
	//      {
	//        ((IStateManager)this._view).TrackViewState();
	//      }
	//    }
	//    return this._view;
	//  }

	//  protected override DataSourceView GetView(string viewName)
	//  {
	//    if ((viewName == null) ||
	//        ((viewName.Length != 0) && !string.Equals(viewName, "DefaultView", StringComparison.OrdinalIgnoreCase)))
	//    {
	//      string errorMessage =
	//        string.Format(
	//          "The data source '{0}' only supports a single view named '{1}'. You may also leave the view name (also called a data member) empty for the default view to be chosen.",
	//          this.ID, "DefaultView");
	//      throw new ArgumentException(errorMessage);
	//    }
	//    return this.GetView();
	//  }

	//  protected override ICollection GetViewNames()
	//  {
	//    if (this._viewNames == null)
	//    {
	//      this._viewNames = new string[] { "DefaultView" };
	//    }
	//    return this._viewNames;
	//  }

	//  public int Insert()
	//  {
	//    return this.GetView().Insert(null);
	//  }

	//  //internal void InvalidateCacheEntry()
	//  //{
	//  //  string key = this.CreateMasterCacheKey();
	//  //  this.Cache.Invalidate(key);
	//  //}

	//  private void LoadCompleteEventHandler(object sender, EventArgs e)
	//  {
	//    this.SelectParameters.UpdateValues(this.Context, this);
	//    this.FilterParameters.UpdateValues(this.Context, this);
	//  }

	//  //internal object LoadDataFromCache(int startRowIndex, int maximumRows)
	//  //{
	//  //  string key = this.CreateCacheKey(startRowIndex, maximumRows);
	//  //  return this.Cache.LoadDataFromCache(key);
	//  //}

	//  //internal int LoadTotalRowCountFromCache()
	//  //{
	//  //  string key = this.CreateMasterCacheKey();
	//  //  object obj2 = this.Cache.LoadDataFromCache(key);
	//  //  if (obj2 is int)
	//  //  {
	//  //    return (int) obj2;
	//  //  }
	//  //  return -1;
	//  //}

	//  protected override void LoadViewState(object savedState)
	//  {
	//    Pair pair = (Pair)savedState;
	//    if (savedState == null)
	//    {
	//      base.LoadViewState(null);
	//    }
	//    else
	//    {
	//      base.LoadViewState(pair.First);
	//      if (pair.Second != null)
	//      {
	//        ((IStateManager)this.GetView()).LoadViewState(pair.Second);
	//      }
	//    }
	//  }

	//  protected override void OnInit(EventArgs e)
	//  {
	//    base.OnInit(e);
	//    if (this.Page != null)
	//    {
	//      this.Page.LoadComplete += new EventHandler(this.LoadCompleteEventHandler);
	//    }
	//  }

	//  //internal void SaveDataToCache(int startRowIndex, int maximumRows, object data)
	//  //{
	//  //  string key = this.CreateCacheKey(startRowIndex, maximumRows);
	//  //  string text2 = this.CreateMasterCacheKey();
	//  //  if (this.Cache.LoadDataFromCache(text2) == null)
	//  //  {
	//  //    this.Cache.SaveDataToCache(text2, -1);
	//  //  }
	//  //  CacheDependency dependency = new CacheDependency(0, new string[0], new string[] {text2});
	//  //  this.Cache.SaveDataToCache(key, data, dependency);
	//  //}

	//  //internal void SaveTotalRowCountToCache(int totalRowCount)
	//  //{
	//  //  string key = this.CreateMasterCacheKey();
	//  //  this.Cache.SaveDataToCache(key, totalRowCount);
	//  //}

	//  protected override object SaveViewState()
	//  {
	//    Pair pair = new Pair();
	//    pair.First = base.SaveViewState();
	//    if (this._view != null)
	//    {
	//      pair.Second = ((IStateManager)this._view).SaveViewState();
	//    }
	//    if ((pair.First == null) && (pair.Second == null))
	//    {
	//      return null;
	//    }
	//    return pair;
	//  }

	//  public IEnumerable Select()
	//  {
	//    return this.GetView().Select(DataSourceSelectArguments.Empty);
	//  }

	//  protected override void TrackViewState()
	//  {
	//    base.TrackViewState();
	//    if (this._view != null)
	//    {
	//      ((IStateManager)this._view).TrackViewState();
	//    }
	//  }

	//  public int Update()
	//  {
	//    return this.GetView().Update(null, null, null);
	//  }

	//  // Properties
	//  //internal SqlDataSourceCache Cache
	//  //{
	//  //    get
	//  //    {
	//  //        if (this._cache == null)
	//  //        {
	//  //            this._cache = new SqlDataSourceCache();
	//  //        }
	//  //        return this._cache;
	//  //    }
	//  //}

	//  //[TypeConverter(typeof (DataSourceCacheDurationConverter)),
	//  // //WebCategory("Cache"), WebSysDescription("DataSourceCache_Duration"),
	//  // DefaultValue(0)]
	//  //public virtual int CacheDuration
	//  //{
	//  //  get { return this.Cache.Duration; }
	//  //  set { this.Cache.Duration = value; }
	//  //}

	//  //[WebSysDescription("DataSourceCache_ExpirationPolicy"), DefaultValue(0), WebCategory("Cache")]
	//  //public virtual DataSourceCacheExpiry CacheExpirationPolicy
	//  //{
	//  //  get { return this.Cache.ExpirationPolicy; }
	//  //  set { this.Cache.ExpirationPolicy = value; }
	//  //}

	//  //[WebSysDescription("DataSourceCache_KeyDependency"), WebCategory("Cache"), DefaultValue("")]
	//  //public virtual string CacheKeyDependency
	//  //{
	//  //  get { return this.Cache.KeyDependency; }
	//  //  set { this.Cache.KeyDependency = value; }
	//  //}

	//  //[WebSysDescription("ObjectDataSource_ConflictDetection"), WebCategory("Data"), DefaultValue(0)]
	//  //public ConflictOptions ConflictDetection
	//  //{
	//  //  get { return this.GetView().ConflictDetection; }
	//  //  set { this.GetView().ConflictDetection = value; }
	//  //}

	//  [//WebCategory("Data"), WebSysDescription("ObjectDataSource_ConvertNullToDBNull"), 
	//  DefaultValue(false)]
	//  public bool ConvertNullToDBNull
	//  {
	//    get { return this.GetView().ConvertNullToDBNull; }
	//    set { this.GetView().ConvertNullToDBNull = value; }
	//  }

	//  [DefaultValue("")
	//    //, WebCategory("Data"), WebSysDescription("ObjectDataSource_DataObjectTypeName")
	//  ]
	//  public string DataObjectTypeName
	//  {
	//    get { return this.GetView().DataObjectTypeName; }
	//    set { this.GetView().DataObjectTypeName = value; }
	//  }

	//  [DefaultValue(""),
	//    //WebSysDescription("ObjectDataSource_DeleteMethod"), WebCategory("Data")
	//  ]
	//  public string DeleteMethod
	//  {
	//    get { return this.GetView().DeleteMethod; }
	//    set { this.GetView().DeleteMethod = value; }
	//  }

	//  [DefaultValue((string)null), PersistenceMode(PersistenceMode.InnerProperty),
	//    //WebCategory("Data"), WebSysDescription("ObjectDataSource_DeleteParameters"), MergableProperty(false),
	//   Editor("System.Web.UI.Design.WebControls.ParameterCollectionEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
	//    , typeof(UITypeEditor))]
	//  public ParameterCollection DeleteParameters
	//  {
	//    get { return this.GetView().DeleteParameters; }
	//  }

	//  //[DefaultValue(false)
	//  ////, WebSysDescription("DataSourceCache_Enabled"), WebCategory("Cache")
	//  //]
	//  //public virtual bool EnableCaching
	//  //{
	//  //  get { return this.Cache.Enabled; }
	//  //  set { this.Cache.Enabled = value; }
	//  //}

	//  [
	//    //WebSysDescription("ObjectDataSource_EnablePaging"), WebCategory("Paging"), 
	//  DefaultValue(false)]
	//  public bool EnablePaging
	//  {
	//    get { return this.GetView().EnablePaging; }
	//    set { this.GetView().EnablePaging = value; }
	//  }

	//  [//WebSysDescription("ObjectDataSource_FilterExpression"), WebCategory("Data"), 
	//  DefaultValue("")]
	//  public string FilterExpression
	//  {
	//    get { return this.GetView().FilterExpression; }
	//    set { this.GetView().FilterExpression = value; }
	//  }

	//  [Editor("System.Web.UI.Design.WebControls.ParameterCollectionEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
	//    , typeof(UITypeEditor)),
	//    //WebCategory("Data"), WebSysDescription("ObjectDataSource_FilterParameters"),
	//   PersistenceMode(PersistenceMode.InnerProperty), MergableProperty(false), DefaultValue((string)null)]
	//  public ParameterCollection FilterParameters
	//  {
	//    get { return this.GetView().FilterParameters; }
	//  }

	//  [DefaultValue("")
	//    //WebCategory("Data"), , WebSysDescription("ObjectDataSource_InsertMethod")
	//  ]
	//  public string InsertMethod
	//  {
	//    get { return this.GetView().InsertMethod; }
	//    set { this.GetView().InsertMethod = value; }
	//  }

	//  [//WebCategory("Data"), WebSysDescription("ObjectDataSource_InsertParameters"),
	//   Editor("System.Web.UI.Design.WebControls.ParameterCollectionEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
	//    , typeof(UITypeEditor)), MergableProperty(false), PersistenceMode(PersistenceMode.InnerProperty),
	//   DefaultValue((string)null)]
	//  public ParameterCollection InsertParameters
	//  {
	//    get { return this.GetView().InsertParameters; }
	//  }

	//  [DefaultValue("maximumRows")
	//    //WebSysDescription("ObjectDataSource_MaximumRowsParameterName"), , WebCategory("Paging")
	//  ]
	//  public string MaximumRowsParameterName
	//  {
	//    get { return this.GetView().MaximumRowsParameterName; }
	//    set { this.GetView().MaximumRowsParameterName = value; }
	//  }

	//  [DefaultValue("{0}")
	//    //WebSysDescription("DataSource_OldValuesParameterFormatString"), , WebCategory("Data")
	//  ]
	//  public string OldValuesParameterFormatString
	//  {
	//    get { return this.GetView().OldValuesParameterFormatString; }
	//    set { this.GetView().OldValuesParameterFormatString = value; }
	//  }

	//  [DefaultValue("")
	//    //, WebSysDescription("ObjectDataSource_SelectCountMethod"), WebCategory("Paging")
	//  ]
	//  public string SelectCountMethod
	//  {
	//    get { return this.GetView().SelectCountMethod; }
	//    set { this.GetView().SelectCountMethod = value; }
	//  }

	//  [DefaultValue("")
	//    //, WebSysDescription("ObjectDataSource_SelectMethod"), WebCategory("Data")
	//  ]
	//  public string SelectMethod
	//  {
	//    get { return this.GetView().SelectMethod; }
	//    set { this.GetView().SelectMethod = value; }
	//  }

	//  [//WebSysDescription("ObjectDataSource_SelectParameters"), WebCategory("Data"),
	//   PersistenceMode(PersistenceMode.InnerProperty), DefaultValue((string)null),
	//   Editor("System.Web.UI.Design.WebControls.ParameterCollectionEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
	//    , typeof(UITypeEditor)), MergableProperty(false)]
	//  public ParameterCollection SelectParameters
	//  {
	//    get { return this.GetView().SelectParameters; }
	//  }

	//  [DefaultValue("")
	//    //, WebSysDescription("ObjectDataSource_SortParameterName"), WebCategory("Data")
	//  ]
	//  public string SortParameterName
	//  {
	//    get { return this.GetView().SortParameterName; }
	//    set { this.GetView().SortParameterName = value; }
	//  }

	//  //[DefaultValue("")
	//  ////, WebCategory("Cache"), WebSysDescription("SqlDataSourceCache_SqlCacheDependency")
	//  //]
	//  //public virtual string SqlCacheDependency
	//  //{
	//  //  get { return this.Cache.SqlCacheDependency; }
	//  //  set { this.Cache.SqlCacheDependency = value; }
	//  //}

	//  [DefaultValue("startRowIndex")
	//    //, WebSysDescription("ObjectDataSource_StartRowIndexParameterName"), WebCategory("Paging")
	//  ]
	//  public string StartRowIndexParameterName
	//  {
	//    get { return this.GetView().StartRowIndexParameterName; }
	//    set { this.GetView().StartRowIndexParameterName = value; }
	//  }

	//  [DefaultValue("")
	//    //,WebCategory("Data"),  WebSysDescription("ObjectDataSource_TypeName")
	//  ]
	//  public string TypeName
	//  {
	//    get { return this.GetView().TypeName; }
	//    set { this.GetView().TypeName = value; }
	//  }

	//  [DefaultValue("")
	//    //, WebSysDescription("ObjectDataSource_UpdateMethod"), WebCategory("Data")
	//  ]
	//  public string UpdateMethod
	//  {
	//    get { return this.GetView().UpdateMethod; }
	//    set { this.GetView().UpdateMethod = value; }
	//  }

	//  [PersistenceMode(PersistenceMode.InnerProperty), DefaultValue((string)null),
	//   Editor(
	//    "System.Web.UI.Design.WebControls.ParameterCollectionEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
	//   , typeof(UITypeEditor)), MergableProperty(false),
	//    //WebCategory("Data"), WebSysDescription("ObjectDataSource_UpdateParameters")
	//  ]
	//  public ParameterCollection UpdateParameters
	//  {
	//    get { return this.GetView().UpdateParameters; }
	//  }
	//}
#endregion

//[SecurityPermission(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)]
public class MyODSDesigner : DataSourceDesigner
{
		// Fields
	//private bool _forceSchemaRetrieval;
	//private Type _selectMethodReturnType;
	//private bool _inWizard;
	//private const string DesignerStateDataSourceSchemaKey = "DataSourceSchema";
	//  private const string DesignerStateDataSourceSchemaSelectMethodKey = "DataSourceSchemaSelectMethod";

	//private const string DesignerStateDataSourceSchemaSelectMethodReturnTypeNameKey =
	//    "DataSourceSchemaSelectMethodReturnTypeName";

	//  private const string DesignerStateDataSourceSchemaTypeNameKey = "DataSourceSchemaTypeName";
	//  private const string DesignerStateShowOnlyDataComponentsStateKey = "ShowOnlyDataComponentsState";

	//  internal const BindingFlags MethodFilter =
	//    (BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance);

		public MyODSDesigner()
		{
			Logger.Log("MyODSDesigner .ctor");
		}

		// Methods
		public override void Configure()
		{
			//this._inWizard = true;
			InvokeTransactedChange(base.Component,
			                       new TransactedChangeCallback(this.ConfigureDataSourceChangeCallback), null,
			                       SR.GetString("DataSource_ConfigureTransactionDescription"));
			//this._inWizard = false;
		}

		private bool ConfigureDataSourceChangeCallback(object context)
		{
			try
			{
				this.SuppressDataSourceEvents();
				//IServiceProvider serviceProvider = base.Component.Site;
				//ObjectDataSourceWizardForm form = new ObjectDataSourceWizardForm(serviceProvider, this);
				//if (UIServiceHelper.ShowDialog(serviceProvider, form) == DialogResult.OK)
				{
					MessageBox.Show("ConfigureDataSourceChangeCallback");
					this.OnDataSourceChanged(EventArgs.Empty);
					return true;
				}
			}
			catch(Exception e)
			{
				Logger.Log(e.ToString());
				return false;				
			}
			finally
			{
				this.ResumeDataSourceEvents();
			}
		}

        private static DataTable[] ConvertSchemaToDataTables(TypeSchema schema)
        {
            if (schema == null)
            {
                return null;
            }
            IDataSourceViewSchema[] views = schema.GetViews();
            if (views == null)
            {
                return null;
            }
            DataTable[] tableArray = new DataTable[views.Length];
            for (int i = 0; i < views.Length; i++)
            {
                IDataSourceViewSchema schema2 = views[i];
                tableArray[i] = new DataTable(schema2.Name);
                IDataSourceFieldSchema[] fields = schema2.GetFields();
                if (fields != null)
                {
                    List<DataColumn> list = new List<DataColumn>();
                    for (int j = 0; j < fields.Length; j++)
                    {
                        IDataSourceFieldSchema schema3 = fields[j];
                        DataColumn column = new DataColumn();
                        column.AllowDBNull = schema3.Nullable;
                        column.AutoIncrement = schema3.Identity;
                        column.ColumnName = schema3.Name;
                        column.DataType = schema3.DataType;
                        if (column.DataType == typeof(string))
                        {
                            column.MaxLength = schema3.Length;
                        }
                        column.ReadOnly = schema3.IsReadOnly;
                        column.Unique = schema3.IsUnique;
                        tableArray[i].Columns.Add(column);
                        if (schema3.PrimaryKey)
                        {
                            list.Add(column);
                        }
                    }
                    if (list.Count > 0)
                    {
                        tableArray[i].PrimaryKey = list.ToArray();
                    }
                }
            }
            return tableArray;
        }

        private static Parameter CreateMergedParameter(ParameterInfo methodParameter, Parameter[] parameters)
        {
            foreach (Parameter parameter in parameters)
            {
                if (ParametersMatch(methodParameter, parameter))
                {
                    return parameter;
                }
            }
            Parameter parameter2 = new Parameter(methodParameter.Name);
            if (methodParameter.IsOut)
            {
                parameter2.Direction = ParameterDirection.Output;
            }
            else if (methodParameter.ParameterType.IsByRef)
            {
                parameter2.Direction = ParameterDirection.InputOutput;
            }
            else
            {
                parameter2.Direction = ParameterDirection.Input;
            }
            parameter2.Type = GetTypeCodeForType(methodParameter.ParameterType);
            return parameter2;
        }

        internal static Type GetType(IServiceProvider serviceProvider, string typeName, bool silent)
        {
            ITypeResolutionService service = null;
            if (serviceProvider != null)
            {
                service = (ITypeResolutionService)serviceProvider.GetService(typeof(ITypeResolutionService));
            }
            if (service == null)
            {
                return null;
            }
            try
            {
                return service.GetType(typeName, true, true);
            }
            catch (Exception exception)
            {
                //if (!silent)
                //{
                //  UIServiceHelper.ShowError(serviceProvider, exception,
                //                            SR.GetString("MyODSDesigner_CannotGetType", new object[] {typeName}));
                //}
                Logger.Log(exception.ToString());
                return null;
            }
        }

        private static TypeCode GetTypeCodeForType(Type type)
        {
            if (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(Nullable<>)))
            {
                type = type.GetGenericArguments()[0];
            }
            else if (type.IsByRef)
            {
                type = type.GetElementType();
            }
            if (typeof(bool).IsAssignableFrom(type))
            {
                return TypeCode.Boolean;
            }
            if (typeof(byte).IsAssignableFrom(type))
            {
                return TypeCode.Byte;
            }
            if (typeof(char).IsAssignableFrom(type))
            {
                return TypeCode.Char;
            }
            if (typeof(DateTime).IsAssignableFrom(type))
            {
                return TypeCode.DateTime;
            }
            if (typeof(DBNull).IsAssignableFrom(type))
            {
                return TypeCode.DBNull;
            }
            if (typeof(decimal).IsAssignableFrom(type))
            {
                return TypeCode.Decimal;
            }
            if (typeof(double).IsAssignableFrom(type))
            {
                return TypeCode.Double;
            }
            if (typeof(short).IsAssignableFrom(type))
            {
                return TypeCode.Int16;
            }
            if (typeof(int).IsAssignableFrom(type))
            {
                return TypeCode.Int32;
            }
            if (typeof(long).IsAssignableFrom(type))
            {
                return TypeCode.Int64;
            }
            if (typeof(sbyte).IsAssignableFrom(type))
            {
                return TypeCode.SByte;
            }
            if (typeof(float).IsAssignableFrom(type))
            {
                return TypeCode.Single;
            }
            if (typeof(string).IsAssignableFrom(type))
            {
                return TypeCode.String;
            }
            if (typeof(ushort).IsAssignableFrom(type))
            {
                return TypeCode.UInt16;
            }
            if (typeof(uint).IsAssignableFrom(type))
            {
                return TypeCode.UInt32;
            }
            if (typeof(ulong).IsAssignableFrom(type))
            {
                return TypeCode.UInt64;
            }
            return TypeCode.Object;
        }

	public override DesignerDataSourceView GetView(string viewName)
	{
        string[] viewNames = this.GetViewNames();
        if ((viewNames == null) || (viewNames.Length <= 0))
        {
            return new ObjectDesignerDataSourceView(this, string.Empty);
        }
        if (string.IsNullOrEmpty(viewName))
        {
            viewName = viewNames[0];
        }
        foreach (string text in viewNames)
        {
            if (string.Equals(viewName, text, StringComparison.OrdinalIgnoreCase))
            {
                return new ObjectDesignerDataSourceView(this, viewName);
            }
        }
		Logger.Log("GetView(string viewName)");
		return null;
	}

		public override string[] GetViewNames()
		{
			Logger.Log("GetViewNames()");
			List<string> list = new List<string>();
            DataTable[] tableArray = this.LoadSchema();
            if ((tableArray != null) && (tableArray.Length > 0))
            {
                foreach (DataTable table in tableArray)
                {
                    list.Add(table.TableName);
                }
            }
			return list.ToArray();
		}

        internal static bool IsMatchingMethod(MethodInfo method, string methodName, ParameterCollection parameters,
                                              Type dataObjectType)
        {
            if (!string.Equals(methodName, method.Name, StringComparison.OrdinalIgnoreCase))
            {
                return false;
            }
            ParameterInfo[] infoArray = method.GetParameters();
            if ((dataObjectType == null) ||
                (((infoArray.Length != 1) || (infoArray[0].ParameterType != dataObjectType)) &&
                 (((infoArray.Length != 2) || (infoArray[0].ParameterType != dataObjectType)) ||
                  (infoArray[1].ParameterType != dataObjectType))))
            {
                if (infoArray.Length != parameters.Count)
                {
                    return false;
                }
                Hashtable hashtable = new Hashtable(StringComparer.Create(CultureInfo.InvariantCulture, true));
                foreach (Parameter parameter in parameters)
                {
                    if (!hashtable.Contains(parameter.Name))
                    {
                        hashtable.Add(parameter.Name, null);
                    }
                }
                foreach (ParameterInfo info in infoArray)
                {
                    if (!hashtable.Contains(info.Name))
                    {
                        return false;
                    }
                }
            }
            return true;
        }

        internal DataTable[] LoadSchema()
        {
            if (!this._forceSchemaRetrieval)
            {
                string a = base.DesignerState["DataSourceSchemaTypeName"] as string;
                string text2 = base.DesignerState["DataSourceSchemaSelectMethod"] as string;
                if (!string.Equals(a, this.TypeName, StringComparison.OrdinalIgnoreCase) ||
                    !string.Equals(text2, this.SelectMethod, StringComparison.OrdinalIgnoreCase))
                {
                    return null;
                }
            }
            DataTable[] tableArray = null;
            Pair pair = base.DesignerState["DataSourceSchema"] as Pair;
            if (pair != null)
            {
                string[] textArray = pair.First as string[];
                DataTable[] tableArray2 = pair.Second as DataTable[];
                if ((textArray == null) || (tableArray2 == null))
                {
                    return tableArray;
                }
                int length = textArray.Length;
                tableArray = new DataTable[length];
                for (int i = 0; i < length; i++)
                {
                    tableArray[i] = tableArray2[i].Clone();
                    tableArray[i].TableName = textArray[i];
                }
            }
            return tableArray;
        }

        internal static Parameter[] MergeParameters(Parameter[] parameters, MethodInfo methodInfo)
        {
            ParameterInfo[] infoArray = methodInfo.GetParameters();
            Parameter[] parameterArray = new Parameter[infoArray.Length];
            for (int i = 0; i < infoArray.Length; i++)
            {
                ParameterInfo methodParameter = infoArray[i];
                parameterArray[i] = CreateMergedParameter(methodParameter, parameters);
            }
            return parameterArray;
        }

        internal static void MergeParameters(ParameterCollection parameters, MethodInfo methodInfo, Type dataObjectType)
        {
            Parameter[] parameterArray = new Parameter[parameters.Count];
            parameters.CopyTo(parameterArray, 0);
            parameters.Clear();
            if ((methodInfo != null) && (dataObjectType == null))
            {
                foreach (ParameterInfo info in methodInfo.GetParameters())
                {
                    Parameter parameter = CreateMergedParameter(info, parameterArray);
                    if (parameters[parameter.Name] == null)
                    {
                        parameters.Add(parameter);
                    }
                }
            }
        }

        private static bool ParametersMatch(ParameterInfo methodParameter, Parameter parameter)
        {
            if (!string.Equals(methodParameter.Name, parameter.Name, StringComparison.OrdinalIgnoreCase))
            {
                return false;
            }
            switch (parameter.Direction)
            {
                case ParameterDirection.Input:
                    if (!methodParameter.IsOut && !methodParameter.ParameterType.IsByRef)
                    {
                        break;
                    }
                    return false;

                case ParameterDirection.Output:
                    if (methodParameter.IsOut)
                    {
                        break;
                    }
                    return false;

                case ParameterDirection.InputOutput:
                    if (methodParameter.ParameterType.IsByRef)
                    {
                        break;
                    }
                    return false;

                case ParameterDirection.ReturnValue:
                    return false;
            }
            TypeCode typeCodeForType = GetTypeCodeForType(methodParameter.ParameterType);
            return
              ((((typeCodeForType == TypeCode.Object) || (typeCodeForType == TypeCode.Empty)) &&
                ((parameter.Type == TypeCode.Object) || (parameter.Type == TypeCode.Empty))) ||
               (typeCodeForType == parameter.Type));
        }

        protected override void PreFilterProperties(IDictionary properties)
        {
            base.PreFilterProperties(properties);
            PropertyDescriptor oldPropertyDescriptor = (PropertyDescriptor)properties["TypeName"];
            properties["TypeName"] = TypeDescriptor.CreateProperty(base.GetType(), oldPropertyDescriptor, new Attribute[0]);
            oldPropertyDescriptor = (PropertyDescriptor)properties["SelectMethod"];
            properties["SelectMethod"] = TypeDescriptor.CreateProperty(base.GetType(), oldPropertyDescriptor, new Attribute[0]);
        }

		public override void RefreshSchema(bool preferSilent)
		{
            try
            {
                Logger.Log("RefreshSchema(bool preferSilent)");
                this.SuppressDataSourceEvents();
                Cursor current = Cursor.Current;
                try
                {
                    Cursor.Current = Cursors.WaitCursor;
                    Type type = GetType(base.Component.Site, this.TypeName, preferSilent);
                    if (type != null)
                    {
                        MethodInfo[] methods =
                          type.GetMethods(BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance);
                        MethodInfo info = null;
                        MethodInfo info2 = null;
                        bool flag = false;
                        Type dataObjectType = null;
                        if (!string.IsNullOrEmpty(this.MyDataSource.DataObjectTypeName))
                        {
                            dataObjectType = GetType(base.Component.Site, this.MyDataSource.DataObjectTypeName, preferSilent);
                        }
                        foreach (MethodInfo info3 in methods)
                        {
                            if (string.Equals(info3.Name, this.SelectMethod, StringComparison.OrdinalIgnoreCase))
                            {
                                if ((info2 != null) && (info2.ReturnType != info3.ReturnType))
                                {
                                    flag = true;
                                }
                                else
                                {
                                    info2 = info3;
                                }
                                if (IsMatchingMethod(info3, this.SelectMethod, this.MyDataSource.SelectParameters, dataObjectType))
                                {
                                    info = info3;
                                    break;
                                }
                            }
                        }
                        if (((info == null) && (info2 != null)) && !flag)
                        {
                            info = info2;
                        }
                        if (info != null)
                        {
                            this.RefreshSchema(info.ReflectedType, info.Name, info.ReturnType, preferSilent);
                        }
                    }
                }
                finally
                {
                    Cursor.Current = current;
                }
            }
            finally
            {
                this.ResumeDataSourceEvents();
            }
		}

        internal void RefreshSchema(Type objectType, string methodName, Type schemaType, bool preferSilent)
        {
            if (((objectType != null) && !string.IsNullOrEmpty(methodName)) && (schemaType != null))
            {
                try
                {
                    TypeSchema schema = new TypeSchema(schemaType);
                    this._forceSchemaRetrieval = true;
                    DataTable[] tables = this.LoadSchema();
                    this._forceSchemaRetrieval = false;
                    IDataSourceSchema schema2 = (tables == null) ? null : ((IDataSourceSchema)new DataTableArraySchema(tables));
                    this.SaveSchema(objectType, methodName, ConvertSchemaToDataTables(schema), schemaType);
                    DataTable[] tableArray2 = this.LoadSchema();
                    IDataSourceSchema schema3 = (tableArray2 == null)
                                                  ? null
                                                  : ((IDataSourceSchema)new DataTableArraySchema(tableArray2));
                    if (!SchemasEquivalent(schema2, schema3))
                    {
                        this.OnSchemaRefreshed(EventArgs.Empty);
                    }
                }
                catch (Exception exception)
                {
                    //if (!preferSilent)
                    //{
                    //  UIServiceHelper.ShowError(base.Component.Site, exception,
                    //                            SR.GetString("MyODSDesigner_CannotGetSchema",
                    //                                         new object[] {schemaType.FullName}));
                    //}
                    Logger.Log(exception.ToString());
                }
            }
        }

        private void SaveSchema(Type objectType, string methodName, DataTable[] schemaTables, Type schemaType)
        {
            Pair pair = null;
            if (schemaTables != null)
            {
                int length = schemaTables.Length;
                string[] x = new string[length];
                for (int i = 0; i < length; i++)
                {
                    x[i] = schemaTables[i].TableName;
                    schemaTables[i].TableName = "Table" + i.ToString(CultureInfo.InvariantCulture);
                }
                pair = new Pair(x, schemaTables);
            }
            base.DesignerState["DataSourceSchema"] = pair;
            base.DesignerState["DataSourceSchemaTypeName"] = (objectType == null) ? string.Empty : objectType.FullName;
            base.DesignerState["DataSourceSchemaSelectMethod"] = methodName;
            string a = base.DesignerState["DataSourceSchemaSelectMethodReturnTypeName"] as string;
            if (!string.Equals(a, schemaType.FullName, StringComparison.OrdinalIgnoreCase))
            {
                base.DesignerState["DataSourceSchemaSelectMethodReturnTypeName"] = schemaType.FullName;
                this._selectMethodReturnType = schemaType;
            }
        }

		// Properties
		public override bool CanConfigure
		{
			//get { return this.TypeServiceAvailable; }
			get { return true; }
		}

		public override bool CanRefreshSchema
		{
			get
			{
				//if (!string.IsNullOrEmpty(this.TypeName) && !string.IsNullOrEmpty(this.SelectMethod))
				//{
				//  return this.TypeServiceAvailable;
				//}
				return false;
			}
		}

		internal MyDataSource.MyDataSource MyDataSource
		{
		  get { return (MyDataSource.MyDataSource) base.Component; }
		}

		public string SelectMethod
		{
		  get { return ""; }
		  //get { return this.MyDataSource.SelectMethod; }
		  //set
		  //{
		  //  if (value != this.SelectMethod)
		  //  {
		  //    this.MyDataSource.SelectMethod = value;
		  //    this.UpdateDesignTimeHtml();
		  //    if (this.CanRefreshSchema && !this._inWizard)
		  //    {
		  //      this.RefreshSchema(true);
		  //    }
		  //    else
		  //    {
		  //      this.OnDataSourceChanged(EventArgs.Empty);
		  //    }
		  //  }
		  //}
		}

		internal Type SelectMethodReturnType
		{
		  get
		  {
		    if (this._selectMethodReturnType == null)
		    {
		      string text = base.DesignerState["DataSourceSchemaSelectMethodReturnTypeName"] as string;
		      if (!string.IsNullOrEmpty(text))
		      {
		        this._selectMethodReturnType = GetType(base.Component.Site, text, true);
		      }
		    }
		    return this._selectMethodReturnType;
		  }
		}

		internal object ShowOnlyDataComponentsState
		{
		  get { return base.DesignerState["ShowOnlyDataComponentsState"]; }
		  set { base.DesignerState["ShowOnlyDataComponentsState"] = value; }
		}

		public string TypeName
		{
		  get { return ""; }
		  //get { return this.MyDataSource.TypeName; }
		  //set
		  //{
		  //  if (value != this.TypeName)
		  //  {
		  //    this.MyDataSource.TypeName = value;
		  //    this.UpdateDesignTimeHtml();
		  //    if (this.CanRefreshSchema)
		  //    {
		  //      this.RefreshSchema(true);
		  //    }
		  //    else
		  //    {
		  //      this.OnDataSourceChanged(EventArgs.Empty);
		  //    }
		  //  }
		  //}
		}

		private bool TypeServiceAvailable
		{
		  get
		  {
		    IServiceProvider site = base.Component.Site;
		    if (site == null)
		    {
		      return false;
		    }
		    ITypeResolutionService service = (ITypeResolutionService) site.GetService(typeof (ITypeResolutionService));
		    ITypeDiscoveryService service2 = (ITypeDiscoveryService) site.GetService(typeof (ITypeDiscoveryService));
		    if (service == null)
		    {
		      return (service2 != null);
		    }
		    return true;
		  }
		}

		// Nested Types
		private sealed class DataTableArraySchema : IDataSourceSchema
		{
		  // Fields
		  private DataTable[] _tables;

		  // Methods
		  public DataTableArraySchema(DataTable[] tables)
		  {
		    this._tables = tables;
		  }

		  public IDataSourceViewSchema[] GetViews()
		  {
		    DataSetViewSchema[] schemaArray = new DataSetViewSchema[this._tables.Length];
		    for (int i = 0; i < this._tables.Length; i++)
		    {
		      schemaArray[i] = new DataSetViewSchema(this._tables[i]);
		    }
		    return schemaArray;
		  }
		}
}

}